<template>
	<div class="publish_statistics_wrapper">
		<div class="item" v-for="(item, index) in countStatData" :key="index" v-if="!!item.children &&item.children.length > 0">
			<h2>{{ item.name }}投稿统计</h2>
			<div class="stat">
				<dl v-for="(v, i) in item.children" :key="i">
					<dt>{{ v.name }}</dt>
					<dd><countTo :start-val="v.startValue" :end-val="v.endValue" separator="" /></dd>
				</dl>
			</div>
		</div>
	</div>
</template>

<script>
import countTo from 'vue-count-to';
import { getDepartListData } from '@/api/system/depart';
import { getNewsCountByDepart } from '@/api/web/sysNewsContents';
export default {
	components: { countTo },
	data() {
		return {
			departData: [],
			countStatData: []
		};
	},
	mounted() {
		this.initializePage();
	},
	methods: {
		//初始化页面
		async initializePage() {
			await this.getDepartData();
			await this.getNewsCount();
		},
		//获取部门列表
		async getDepartData() {
			let result = await getDepartListData({ pId: '0', extFiled1: '1' }).then((res) => res.data);
			if (result.code === '0') {
				let datas = !result.data ? [] : [...result.data];
				this.departData = datas;
			}
		},

		//获取部门发布文章数量
		async getNewsCount() {
			let flatData = this.$treeToFlat(this.departData).filter((item) => item.level === '2');
			let deptIds = flatData.map((item) => item.id);
			let result = await getNewsCountByDepart({ deptIds, flag: '1' }).then((res) => res.data);
			if (result.code === '0') {
				this.formatNewsCount(!result.data ? {} : { ...result.data[0] });
			}
		},

		//格式化数据
		async formatNewsCount(data) {
			let flatData = this.$treeToFlat(this.countStatData.length > 0 ? this.countStatData : this.departData);
			let countData = flatData.map((item) => {
				let obj = { ...item };
				if (Object.keys(data).some((v) => v === item.id)) {
					this.$set(obj, 'startValue', parseInt(item.endValue || 0));
					this.$set(obj, 'endValue', parseInt(data[item.id]));
				}
				return obj;
			});
			this.countStatData = this.$flatToTree(countData, 'pid');
		}
	}
};
</script>

<style lang="scss" scoped>
.publish_statistics_wrapper {
	margin-bottom: 20px;
	.item {
		min-height: 100px;
		margin-bottom: 20px;
		border-radius: 4px;
		overflow: hidden;
		h2 {
			font-size: 20px;
			color: #fff;
			background-color: #357c65;
			// text-align: center;
			padding: 15px 25px;
		}
		.stat {
			display: flex;
			flex-wrap: wrap;
			flex: 1;
			overflow: hidden;
			padding: 20px 40px;
			background-color: rgba(0, 0, 0, 0.05);
		}
		dl {
			flex: 1;
			min-width: 20%;
			padding: 20px 0;
			dt {
				font-size: 18px;
				color: #666;
				margin-bottom: 10px;
			}
			dd {
				font-size: 32px;
				line-height: 1;
				font-weight: bold;
				color: #e88227;
			}
		}
	}
}
</style>
